<template>
  <!-- 企业管理--项目 -->
  <div class="business">
    <el-form :inline="true"
             :model="dataForm"
             @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.userName"
                  style="width: 330px"
                  placeholder="请输入账号名、企业名称、手机号码、联系人"
                  clearable></el-input>
      </el-form-item>
      <el-form-item>
        <!-- 搜素按钮 -->
        <el-button type="primary"
                   icon="el-icon-search"
                   @click="getDataList()"></el-button>
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="timeInterval"
                        type="daterange"
                        range-separator="-"
                        value-format="yyyy-MM-dd"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   @click="addOrUpdateHandle()">新增</el-button>
        <div class="file">
          <el-upload class="upload-demo"
                     :action="action"
                     :before-upload="beforeAvatarUpload"
                     :on-success="handleAvatarSuccess"
                     :headers='headers'
                     :data='upData'
                     :show-file-list='false'
                     multiple
                     :limit="1"
                     :file-list="fileList">
            <el-button type="info"
                       class="btnColor">批量导入</el-button>
          </el-upload>
        </div>
        <el-button type="info"
                   class="btnColor"
                   :disabled="tableData.length <= 0"
                   @click="export2Excel()">批量导出</el-button>
        <!-- <el-button type="info"
                   @click="deleteHandle()"
                   :disabled="dataListSelections.length <= 0">批量删除</el-button> -->
      </el-form-item>
    </el-form>
    <!-- 表格开始 -->
    <el-table :data="tableData"
              border
              v-loading="dataListLoading"
              @selection-change="selectionChangeHandle"
              style="width: 100%">
      <!-- <el-table-column type="selection"
                       header-align="center"
                       align="center"
                       width="50">
      </el-table-column> -->
      <el-table-column prop="userId"
                       fixed
                       header-align="center"
                       align="center"
                       width="72"
                       label="ID">
      </el-table-column>
      <el-table-column prop="companyLicense"
                       header-align="center"
                       align="center"
                       width="127"
                       label="企业营业执照">
        <template slot-scope="scope">
          <img :src="scope.row.companyLicense"
               class="license_img" />
        </template>
      </el-table-column>
      <el-table-column prop="username"
                       header-align="center"
                       align="center"
                       width="137"
                       label="账号名">
      </el-table-column>
      <el-table-column prop="companyName"
                       header-align="center"
                       align="center"
                       width="204"
                       label="企业名称">
      </el-table-column>
      <el-table-column prop="contactPerson"
                       header-align="center"
                       align="center"
                       width="101"
                       label="联系人">
      </el-table-column>
      <el-table-column prop="mobile"
                       header-align="center"
                       align="center"
                       width="136"
                       label="手机号码">
      </el-table-column>
      <el-table-column prop="bankAccout"
                       header-align="center"
                       align="center"
                       width="199"
                       label="银行账户信息">
      </el-table-column>
      <!-- <el-table-column prop="bakInfo.bankCardNumber"
                       header-align="center"
                       align="center"
                       width="200"
                       label="银行卡号">
      </el-table-column>
       -->
      <el-table-column prop="bankName"
                       header-align="center"
                       align="center"
                       width="200"
                       label="开户银行">
      </el-table-column>
      <el-table-column prop="legalPerson"
                       header-align="center"
                       align="center"
                       width="101"
                       label="法人代表">
      </el-table-column>
      <el-table-column prop="companyAddr"
                       header-align="center"
                       align="center"
                       width="290"
                       label="公司地址">
      </el-table-column>
      <el-table-column label="操作"
                       align="center"
                       fixed="right"
                       width="170">
        <template slot-scope="scope">
          <!-- <el-button type="text"
                     size="small">查询</el-button> -->
          <el-button @click="update(scope.row.userId)"
                     type="text"
                     size="small">修改</el-button>
          <el-button type="text"
                     size="small"
                     v-if="scope.row.status=='1'"
                     @click="frozen(scope.row.userId,scope.row.status)">冻结</el-button>
          <el-button type="text"
                     size="small"
                     v-else
                     @click="frozen(scope.row.userId,scope.row.status)">启用</el-button>
          <el-button type="text"
                     size="small"
                     @click="deleteHandle(scope.row.userId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <!-- 分页前说明 -->
      <div class="instructions">显示第{{tableData.length>0?((pageIndex-1)*pageSize+1):0}}到第{{(pageIndex-1)*pageSize+tableData.length}}条数据，总共{{totalPage}}条数据
      </div>
      <!-- 分页 -->
      <el-pagination @size-change="sizeChangeHandle"
                     @current-change="currentChangeHandle"
                     :current-page="pageIndex"
                     :page-sizes="[10, 20, 50]"
                     :page-size="pageSize"
                     :total="totalPage"
                     layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>

    <!-- 弹窗, 新增 / 修改 -->
    <addBusiness v-if="addOrUpdateVisible"
                 ref="addOrUpdate"
                 @refreshDataList="getDataList"></addBusiness>
  </div>
</template>

<script>
import addBusiness from './add/addBusiness'
export default {
  data () {
    return {
      dataForm: {
        userName: ''
      },
      headers: {
        token: ''
      },
      upData: {
        userRoleId: '2'
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      // 时间区间
      timeInterval: '',
      startTime: '',
      endTime: '',
      // 假数据
      tableData: [],
      // 上传相关
      fileList: [],
      action: ''
    }
  },
  components: {
    addBusiness
  },
  activated () {
    // 上传地址
    this.action = this.$baseUrl + '/sys/user/import'
    this.headers.token = this.$cookie.get('token')
    this.getDataList()
  },
  watch: {
    timeInterval () {
      try {
        this.startTime = this.timeInterval[0]
        this.endTime = this.timeInterval[1]
      } catch (error) {
        this.startTime = ''
        this.endTime = ''
      }
      this.getDataList()
    }
  },
  methods: {
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/sys/user/list'),
        method: 'get',
        params: this.$http.adornParams({
          'type': '2',
          'userName': this.dataForm.userName,
          'page': this.pageIndex,
          'limit': this.pageSize,
          'startTime': this.startTime,
          'endTime': this.endTime
        })
      }).then(({ data }) => {
        this.dataListLoading = false
        this.tableData = data.page.list
        this.totalPage = data.page.totalCount
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 冻结
    frozen (id, status) {
      if (status) {
        status = 0
      } else {
        status = 1
      }
      this.$http({
        url: this.$http.adornUrl('/sys/user/sys-user/forbidden'),
        method: 'post',
        data: this.$http.adornParams({
          status: status,
          userId: id
        })
      }).then(({ data }) => {
        this.$message.success('设置状态成功')
        this.getDataList()
      })
    },
    // 新增
    addOrUpdateHandle () {
      // 显示
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.mode = 'add'
        this.$refs.addOrUpdate.dataForm = {
          bankAccout: '',
          bankName: '',
          // bankAccout: {},
          companyAddr: '',
          companyLicense: '',
          companyName: '',
          contactPerson: '',
          legalPerson: '',
          mobile: '',
          password: '',
          pid: '',
          status: '1',
          username: ''
        }
        this.$refs.addOrUpdate.addInit()
      })
    },
    // 编辑
    update (id) {
      // 显示
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.mode = 'edit'
        this.$refs.addOrUpdate.visible = true
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.userId
      })
      this.$confirm(`确定删除操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除接口
        this.$http({
          url: this.$http.adornUrl('/sys/user/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.pageIndex = 1
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => { })
    },
    // 导入函数
    // 上传前
    beforeAvatarUpload (f) {
      if (!(f.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || f.type === 'application/vnd.ms-excel')) {
        this.$message.error('上传文件只能是 xls和xlsx 格式!')
        return false
      } else {
        return true
      }
    },
    // 导入成功处理函数
    handleAvatarSuccess (res, file) {
      if (res.code === 0) {
        this.$message.success('导入成功')
        this.pageIndex = 1
        this.getDataList()
      } else {
        this.$message.error(res.msg)
      }
      this.fileList = []
    },
    // 导出函数
    export2Excel () {
      this.$http({
        url: this.$http.adornUrl('/sys/user/export'),
        method: 'post',
        responseType: 'blob',
        data: this.$http.adornParams({
          'type': '2',
          'userName': this.dataForm.userName,
          'startTime': this.startTime,
          'endTime': this.endTime
        })
      }).then((_res) => {
        let blob = new Blob([_res.data], {
          type: 'application/vnd.ms-excel'
        })
        let url = window.URL.createObjectURL(blob)
        let a = document.createElement('a')
        a.href = url
        a.download = '企业管理.xlsx'
        a.click()
        window.URL.revokeObjectURL(a.href)
      })
    },
    // 按钮搜索
    search () {
      this.pageIndex = 1
      this.getDataList()
    }
    // 接下来
  }
}
</script>

<style lang="scss" scoped>
.business {
  .pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .instructions {
      height: 19px;
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      line-height: 19px;
      color: #333333;
    }
  }
  .license_img {
    width: 70px;
    height: 50px;
  }
  // 导入
  button.el-button.btnColor.el-button--info.el-button--medium {
    position: relative;
    overflow: hidden;
  }
  .file {
    display: inline;
    position: relative;
    overflow: hidden;
    .fileBtn {
      opacity: 0;
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
    }
    .upload-demo {
      display: inherit;
    }
  }
}
</style>